<script setup>
import { ref, onMounted } from 'vue'
import { getCart } from '@/apis/cart.js'
import { getDefaultAddress, getAddressList } from '@/apis/address.js' // 新增：获取所有地址
import { createOrder } from '@/apis/orders.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()

// 购物车商品
const cartItems = ref([])

// 地址信息
const selectedAddress = ref(null)
const addressList = ref([]) // 所有地址列表
const showAddressSelector = ref(false) // 是否显示地址选择弹窗
// 备注信息
const remark = ref('')

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    const res = await getCart()
    if (res.code === 0) {
      cartItems.value = res.data
    } else {
      ElMessage.error( '获取购物车失败')
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('网络异常，请稍后再试')
  }
}

// 获取默认地址
const fetchDefaultAddress = async () => {
  try {
    const res = await getDefaultAddress()
    if (res.code === 0) {
      selectedAddress.value = res.data
    } else {
      ElMessage.warning('未设置默认地址')
    }
  } catch (error) {
    console.error('获取默认地址失败:', error)
    ElMessage.error('地址加载失败')
  }
}

// 获取所有地址
const fetchAddressList = async () => {
  try {
    const res = await getAddressList()
    if (res.code === 0) {
      addressList.value = res.data
    } else {
      ElMessage.warning('地址列表为空')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('地址加载失败')
  }
}

// 切换地址选择器
const toggleAddressSelector = () => {
  showAddressSelector.value = !showAddressSelector.value
}

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address
  toggleAddressSelector()
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择地址')
    return
  }

  const amount = cartItems.value.reduce((total, item) => total + item.amount, 0)

  const orderData = {
    addressId: selectedAddress.value.id,
    amount,
    remark: remark.value
  }

  try {
    const res = await createOrder(orderData)
    if (res) {
      // 假设后端返回了 OrderSubmitVO 数据
      const order = res.data // 假设 data 包含 id、number、amount、orderTime
      ElMessage.success('下单成功')
      // 携带订单号和金额跳转到支付页
      router.push({
        path: '/payment',
        query: {
          number: order.number,
          amount: order.amount,
          createTime: order.orderTime // 用于计算倒计时
        }
      })
    } else {
      ElMessage.error('下单失败')
    }
  } catch (error) {
    console.error('下单失败:', error)
    ElMessage.error('网络异常，请稍后再试')
  }
}


onMounted(async () => {
  await fetchCartItems()
  await fetchDefaultAddress()
  await fetchAddressList() // 页面加载时获取地址列表
})

</script>


<template>
  <div class="order-detail-container">
    <!-- 商品信息 -->
    <section class="order-products">
      <h3>商品信息</h3>
      <div v-for="(item, index) in cartItems" :key="item.id" class="product-item">
        <img :src="item.image" alt="商品图片" class="product-image" />
        <div class="product-details">
          <span class="product-name">{{ item.name }}</span>
          <span class="product-quantity">数量: {{ item.number }}</span>
          <span class="product-price">价格: {{ item.amount }} 元</span>
          <span class="product-quantity">尺码: {{ item.size }}</span>

        </div>
      </div>
    </section>

    <!-- 地址信息 -->
    <section class="order-address">
      <h3>地址信息</h3>
      <div v-if="selectedAddress" class="address-card">
        <p><strong>收货人:</strong> {{ selectedAddress.consignee }}</p>
        <p><strong>电话:</strong> {{ selectedAddress.phone }}</p>
        <p><strong>地址:</strong> {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.detail }}</p>
        <button class="btn-change" @click="toggleAddressSelector">更换地址</button>
      </div>
      <p v-else class="no-address">请先添加地址</p>

      <!-- 地址选择器弹窗 -->
      <transition name="fade">
        <div v-show="showAddressSelector" class="address-selector">
          <h4>选择地址</h4>
          <ul>
            <li v-for="addr in addressList" :key="addr.id" @click="selectAddress(addr)">
              <strong>{{ addr.consignee }}</strong> - {{ addr.detail }}
            </li>
          </ul>
          <button class="btn-close" @click="toggleAddressSelector">关闭</button>
        </div>
      </transition>
    </section>

    <!-- 备注信息 -->
    <section class="order-remark">
      <label for="remark">备注信息：</label>
      <input id="remark" v-model="remark" placeholder="如：是否需要原装鞋盒、特殊鞋码等" />
    </section>
    <!-- 下单按钮 -->
    <button class="submit-order-btn" @click="submitOrder">下单</button>
    <button class="back-home-btn" @click="$router.push('/')">返回首页</button>
  </div>
</template>




<style scoped lang="scss">
$primary-color: #d4a373;
$light-gray: #f9f9f9;
$border-radius: 6px;
.actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.back-home-btn {
  width: 100%;
  padding: 14px 20px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #e0e0e0;
  }
}

.order-detail-container {
  max-width: 800px;
  margin: 60px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: $border-radius;
  box-shadow: 0 10px 24px rgba(0, 0, 0, 0.08);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 商品信息 */
.order-products {
  margin-bottom: 30px;

  .product-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #eee;
    transition: background 0.2s ease;

    &:hover {
      background: #f9f9f9;
    }

    .product-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 20px;
    }

    .product-details {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 60px;

      .product-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }

      .product-quantity,
      .product-price {
        font-size: 14px;
        color: #777;
      }
    }
  }
}

/* 地址信息 */
.order-address {
  margin-bottom: 30px;

  h3 {
    margin-bottom: 15px;
  }

  .address-card {
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    background-color: $light-gray;
    position: relative;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-2px);
    }

    p {
      margin: 6px 0;
      color: #555;
    }
  }

  .no-address {
    color: #aaa;
    font-style: italic;
  }

  .btn-change {
    margin-top: 10px;
    background: none;
    border: 1px solid $primary-color;
    color: $primary-color;
    padding: 6px 12px;
    font-size: 14px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: lighten($primary-color, 20%);
    }
  }
}

/* 地址选择器弹窗 */
.address-selector {
  margin-top: 15px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-color: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);

  h4 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 16px;
    color: #333;
  }

  ul {
    list-style: none;
    padding: 0;
    margin-bottom: 15px;

    li {
      padding: 10px 12px;
      border-bottom: 1px solid #eee;
      cursor: pointer;
      transition: background 0.2s ease;

      &:hover {
        background-color: #f0f0f0;
      }
    }

    li:last-child {
      border-bottom: none;
    }
  }

  .btn-close {
    background: #f0f0f0;
    color: #333;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background: #eaeaea;
    }
  }
}

/* 备注信息 */
.order-remark {
  margin-bottom: 30px;

  label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    color: #555;
  }

  input {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.3s ease;

    &:focus {
      border-color: $primary-color;
      outline: none;
      box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
    }
  }
}

/* 下单按钮 */
.submit-order-btn {
  width: 100%;
  padding: 14px 20px;
  background: linear-gradient(to right, lighten($primary-color, 6%), darken($primary-color, 6%));
  color: white;
  border: none;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba($primary-color, 0.2);
  }

  &:active {
    transform: scale(0.98);
  }
}
</style>
